import json

import itchat
import requests
from itchat.content import *

def send_post_request(msg):
    data = {
        "uId": msg.FromUserName,
        "msg": msg.text
    }
    # 构造要发送的数据，并将其转换为JSON格式
    json_data = json.dumps(data)

    # 发送POST请求
    response = requests.post("http://xxxx:xx/chat/", data=json_data, headers={'Content-Type': 'application/json'})

    # 返回响应结果
    return hald_response(response.text)

def hald_response(text):
    text = text.replace("\"", "\\\"")
    return text


@itchat.msg_register([TEXT, MAP, CARD, NOTE, SHARING])
def text_reply(msg):
    print(json.dumps(msg))
    if msg.type == 'Text':
        msg.user.send(send_post_request(msg))

# @itchat.msg_register([PICTURE, RECORDING, ATTACHMENT, VIDEO])
# def download_files(msg):
#     msg.download(msg.fileName)
#     typeSymbol = {
#         PICTURE: 'img',
#         VIDEO: 'vid', }.get(msg.type, 'fil')
#     return '@%s@%s' % (typeSymbol, msg.fileName)

# @itchat.msg_register(FRIENDS)
# def add_friend(msg):
#     if is_reply == False:
#         return
#     msg.user.verify()
#     msg.user.send('Nice to meet you!')
#
@itchat.msg_register(TEXT, isGroupChat=True)
def text_reply(msg):
    print(json.dumps(msg))
    if msg.isAt:
        msg.user.send(u'@%s\u2005%s' % (
            msg.actualNickName, send_post_request(msg)))
    else:
        if msg.text.startswith(' '):
            msg.user.send(send_post_request(msg))

if __name__ == '__main__':
    itchat.auto_login(True, enableCmdQR=2)
    itchat.run()
    itchat.send('机器人【%s】已上线''' % itchat.instance.storageClass.nickName, toUserName="filehelper")


